#include <head.h>

int main(int argc, char const *argv[])
{
    int p_fd[2];
    if (-1 == pipe(p_fd))
    {
        perror("pipe error:");
        return -1;
    }

    pid_t pid;

    if (-1 == (pid = fork()))
    {
        perror("fork error");
        close(p_fd[0]);
        close(p_fd[1]);
        return -1;
    }
    else if (0 < pid) // 父进程写入
    {
        // 关闭 读端
        close(p_fd[0]); // 关闭读端
        char buf_write[128];
        while (1)
        {
            memset(buf_write, 0, sizeof(buf_write));
            printf("父进程 输入想要写入的数据\n");
            scanf("%s", buf_write);
            write(p_fd[1], buf_write, sizeof(buf_write));
            if (!strcmp(buf_write, "quit"))
            {
                break;
            }
            usleep(50000);
        }
        close(p_fd[1]);
    }

    if (0 == pid) // 子进程读取
    {
        close(p_fd[1]);
        char buf_read[128];
        while (1)
        {
            memset(buf_read, 0, sizeof(buf_read));
            read(p_fd[0], buf_read, sizeof(buf_read));
            if (strlen(buf_read) == 0)
            {
                continue;
            }
            if (!strcmp(buf_read, "quit"))
            {
                break;
            }
            printf("子进程 读取的数据为: %s\n", buf_read);
        }
        close(p_fd[0]);
    }

    return 0;
}
